package com.gxc.controller;

import com.gxc.entity.User;
import com.gxc.entity.UserDto;
import com.gxc.jpa.UserRepository;
import com.gxc.service.UserService;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * UserController.
 *
 * @author 宫新程
 * @since 2019/1/18 11:33 PM
 */
@RestController
public class UserController {

  @Resource private UserRepository userRepository;
  @Resource private UserService userService;

  @GetMapping("/user")
  public List<User> findAll() {
    return userRepository.findAll();
  }

  /** 多条件查询. */
  @PostMapping("/search")
  public List<User> search(@RequestBody User user) {
    Specification<User> specification =
        (root, criteriaQuery, cb) -> {
          List<Predicate> list = new ArrayList<>();
          if (!isEmpty(user.getUsername())) {
            Predicate username =
                cb.like(root.get("username").as(String.class), "%" + user.getUsername() + "%");
            list.add(username);
          }

          if (!isEmpty(user.getPassword())) {
            Predicate password =
                cb.like(root.get("password").as(String.class), "%" + user.getPassword() + "%");
            list.add(password);
          }

          Predicate[] array = new Predicate[list.size()];
          return cb.and(list.toArray(array));
        };
    return userRepository.findAll(specification);
  }

  /** 保存 / 更新. */
  @PutMapping("/user")
  public List<User> save(@RequestBody List<User> userList) {
    return userRepository.saveAll(userList);
  }

  /** 根据id查询. */
  @GetMapping("/user/{id}")
  public User findById(@PathVariable Integer id) {
    return userRepository.findByUserId(id);
  }

  @DeleteMapping("/user/{id}")
  public Boolean deleteById(@PathVariable Integer id) {
    userRepository.deleteByUserId(id);
    return true;
  }

  private boolean isEmpty(String str) {
    return str == null || "".equals(str);
  }


  /**
   *  1：使用User实体接收 做新增或者更新操作.
   *
   *  前提：主键生成策略：@GeneratedValue(strategy = GenerationType.IDENTITY)
   *  结论：
   *    （1）如果设置了id，如果这个id 在mysql中已经存在，则会做更新操作。
   *    （2）如果设置了id，如果id在mysql中不存在，则做新增操作，mysql会自动生成一个主键id，无论是否设置了id
   *    （3）如果没有设置id，则做新增操作，mysql会自动生成一个主键id
   * */
  @PutMapping("/entity/user")
  public Object updateEntityUser(@RequestBody User user) {
    return userService.updateEntityUser(user);
  }

  @PutMapping("/service/user")
  public Object updateServiceUser() {
    return userService.updateServiceUser();
  }

  @PutMapping("/dto/userDto")
  public Object updateServiceUser(@RequestBody UserDto userDto) {
    return userService.updateDaoUser(userDto);
  }
}
